<template>

  <v-form ref="myBrandForm" v-model="valid">
    <v-text-field
      v-model="brand.name"
      :rules="[rules.required, rules.nameLen]"
      label="品牌名称"
      required
    ></v-text-field>
    <v-text-field
      v-model="brand.letter"
      :rules="[rules.letter]"
      label="品牌首字母"
      required
    ></v-text-field>
    <v-cascader
      url="/item/category/list"
      multiple required
      v-model="brand.categories"
      label="请选择商品分类"/>
    <v-layout row>
      <v-flex xs4>
        上传LOGO：
      </v-flex>
      <v-flex xs9>
        <v-upload
          v-model="brand.image"
          url="/upload/image"
          :multiple="false"
          :pic-width="170"
          :pic-height="60"
        />
      </v-flex>
    </v-layout>
    <v-layout row mt-3>
      <v-spacer />
      <v-flex xs6>
        <v-btn color="primary" @click="reset()">重置</v-btn>
        <v-btn color="primary" @click="submit()">提交</v-btn>
      </v-flex>
    </v-layout>
  </v-form>
</template>

<script>
  export default {
    name: "MyBrandForm",
    data() {
      return {
        valid: {},
        brand: {
          name: "",
          letter: "",
          image: "",
          categories: []
        },
        rules: {
          required: value=>!!value || "required",
          nameLen: value=>value.length < 10 || "长度不能大于10位",
          letter: value=>/^[A-Z]{1}$/.test(value) || "首字母必须是大写"
        }
      }
    },
    methods: {
      closeWin(){
        this.$emit("close");
      },
      submit(){
        console.log(this.$qs);
        if(this.valid){
          // 去除brand对象中的某些属性，其他属性解析到...params中
          const {categories, ...params} = this.brand;

          params.cids = categories.map(c=>c.id).join(",");
          this.$http.post("/item/brand", this.$qs.stringify(params)).then(resp=>{
            // 关闭窗口
            this.closeWin();
            // 提示成功
            this.$message.success("品牌新增成功！")

          }).catch(()=>{
            this.$message.error("品牌新增失败！");
          })
        }
      },
      reset(){
        this.brand.categories=[];
        this.$refs.myBrandForm.reset();
      }
    }
  }
</script>

<style scoped>

</style>
